#include<stdio.h>
#include"cJSON.h"
#include <stdlib.h>

int main(int argc, char const *argv[])
{
#if 1
  //打开文件
   FILE *file= fopen("data.json","r");
   if (file==NULL)
   {
    perror("open err\n");
    return -1;
   }

   char buf[1024]={0};

   size_t len= fread(buf,1,1024,file);
   if (len<0)
   {
    perror("read err\n");
    return -1;
   }
   
   fclose(file);
   
  cJSON *root=cJSON_Parse(buf);
   if (root==NULL)
   {
    printf("parse err\n");
    return -1;
   }
   cJSON *item=cJSON_GetObjectItem(root,"ver");
   printf("ver=%s\n",item->valuestring);
   
   cJSON *login=cJSON_GetObjectItem(root,"login");
   cJSON *pwd=cJSON_GetObjectItem(login,"pwd");
   printf("%s=%d\n",pwd->string,pwd->valueint);

   cJSON *data=cJSON_GetObjectItem(root,"data");
   int	count=  cJSON_GetArraySize(data);

   for (size_t i = 0; i < count; i++)
   {
    cJSON *tmp=cJSON_GetArrayItem(data, i);

    item=cJSON_GetObjectItem(tmp,"key");
    printf("key=%d\n",item->valueint);
     item=cJSON_GetObjectItem(tmp,"type");
    printf("type=%d\n",item->valueint);
     item=cJSON_GetObjectItem(tmp,"val");
    printf("val=%s\n",item->valuestring);

   }
  
   //释放整棵树的内存
    cJSON_Delete(root);
    return 0;
#else
  cJSON *root=cJSON_CreateObject();//创建树 

  cJSON *item=cJSON_CreateString("小明");//创建果实
  cJSON_AddItemToObject(root, "name", item);// 子节点添加到根节点

  cJSON_AddItemToObject(root, "age", cJSON_CreateNumber(14));

   cJSON_AddItemToObject(root, "gender", cJSON_CreateTrue());


   cJSON *buf=cJSON_CreateArray();//创建数组节点
   cJSON_AddItemToArray(buf,  cJSON_CreateString("java"));
   cJSON_AddItemToArray(buf,  cJSON_CreateString("LIsp"));
   cJSON_AddItemToArray(buf,  cJSON_CreateString("Python"));

  cJSON_AddItemToObject(root, "skills", buf);


    //把上面的树，转换成字符串
    char *p = cJSON_Print(root);
    printf("%s\n", p);
    free(p);

    //释放内存
    cJSON_Delete(root);
  return 0;

#endif
}
